
import java.io.*;
import java.util.ArrayList;
/**
 *
 * @author Adam Dickinson
 */
public class UserMail implements Serializable {
    private final String filename;
    private String username;
    
    private ArrayList<Message> messages;
    
    public UserMail(String user) {
        username = user;
        filename = user + "mail";
        messages = new ArrayList<Message>();
    }
    
    public void add(Message message) {
        messages.add(message);
    }
    
    public void create(String username) {
        
    }
    
    public void delete(int index) {
        messages.remove(index);
    }
    
    public Message find(int index) {
        return messages.get(index);
    }
    
    public Message find(String ind)
    {
        int index = Integer.parseInt(ind.trim()) -1;
        return messages.get(index);
    }
    
    public void save() throws Exception {
        ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream(filename));
        save.writeObject(this);
        save.close();
    }
    
    
    public int size() {
        return messages.size();
    }
    
    public ArrayList<Message> getMessages()
    {
        return this.messages;
    }
    // method for list POP3
    public String getAllEmails(){
        
        
        String details =""; 
	
        
        for(int x=0; x < messages.size(); x++)
        {
            Message email = messages.get(x);
            details += (" " + (x+1) + ". " + email.getBody().length());
            details += '\n';
            
        }
        
        details +=".";
        
        return details; 
        
    }
    
    
    
    public String toWebString() {
        
        String ret = "Inbox for : " + username  + "<br />";
        ret += size() + " emails.<br />";
        
        if (size() > 0) {
            for (int i = 0; i < messages.size(); i++) {
                Message email = messages.get(i);
                ret += "<a href = \"/" + username + "/" +
                        i + "/\">";
                ret += "Email " + (i + 1) + ": Sent from " + email.getFrom();
                ret += "</a><br />";                
            }
        }
        
        return ret;
    }
    
    public static UserMail open(String username) {
        
        try{
        ObjectInputStream input = new ObjectInputStream(new FileInputStream(username + "mail"));
        return (UserMail)input.readObject();
        }
        catch(Exception ex)
        {
 
			UserMail user = new UserMail(username);
            return user;  
        }
    }
}
